package com.jc.order.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.jc.order.config.OSSConf;
import com.jc.util.Result;
import com.jc.vo.FileResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("fileUpload/v1")
@Slf4j
public class FileUploadController {

    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    // 禁止上传的文件后缀列表
    private static final Set<String> FORBIDDEN_EXTENSIONS = Arrays.stream(new String[]{
            "jsp", "exe", "dll", "bat", "sh", "js", "php", "asp", "aspx"
    }).collect(Collectors.toSet());

    @Resource
    private OSSConf ossConf;

    @PostMapping("/upload")
    public Result<FileResponse> upload(@RequestParam("file") MultipartFile file) {
        // 1. 文件空校验
//        if (file.isEmpty()) {
//            return new Result().error("上传文件不能为空");
//        }
//
        String originalFilename = file.getOriginalFilename();
//        if (originalFilename == null || originalFilename.trim().isEmpty()) {
//            return new Result().error("文件名不能为空");
//        }

        // 2. 文件后缀校验
        String fileExtension = getFileExtension(originalFilename);
        if (isForbiddenExtension(fileExtension)) {
            return new Result().error("禁止上传该类型的文件: " + fileExtension);
        }

        // 3. 文件大小校验（严格限制10MB）
        if (file.getSize() > MAX_FILE_SIZE) {
            return new Result().error("文件大小不能超过10MB");
        }

        // 4. 文件类型校验（可选）
//        String contentType = file.getContentType();
//        if (contentType == null || !contentType.startsWith("image/")) {
//            return new Result().error("只支持图片文件上传");
//        }

        String fileName = null;
        try (InputStream inputStream = file.getInputStream()) {
            // 5. 生成唯一文件名
            fileName = generateUniqueFileName(originalFilename, fileExtension);

            // 6. 创建OSS客户端
            OSS ossClient = new OSSClientBuilder().build(
                    ossConf.getEndpoint(),
                    ossConf.getAccessKeyId(),
                    ossConf.getAccessKeySecret()
            );

            try {
                // 7. 执行上传
                PutObjectRequest putRequest = new PutObjectRequest(
                        ossConf.getBucketName(),
                        fileName,
                        inputStream
                );
                ossClient.putObject(putRequest);

                // 8. 生成访问URL
                String fileUrl = generateFileUrl(fileName);

                // 9. 返回成功响应
                return createSuccessResponse(file, fileName, fileUrl);
            } finally {
                // 10. 关闭OSS客户端
                ossClient.shutdown();
            }
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return new Result().error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件扩展名（小写形式）
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(Locale.ENGLISH);
    }

    /**
     * 检查是否是禁止的文件扩展名
     */
    private boolean isForbiddenExtension(String extension) {
        return FORBIDDEN_EXTENSIONS.contains(extension);
    }

    /**
     * 创建成功响应
     */
    private Result<FileResponse> createSuccessResponse(MultipartFile file, String fileName, String fileUrl) {
        log.info("文件上传成功: {} => {} (大小: {}KB)",
                file.getOriginalFilename(),
                fileName,
                file.getSize() / 1024);

        FileResponse response = new FileResponse();
        response.setFileName(file.getOriginalFilename());
        response.setFileSize(file.getSize());
        response.setFullPathName(fileUrl);
        response.setContentType(file.getContentType());
        response.setOssKey(fileName);


//        FileUploadResponse fileUploadResponse=new FileUploadResponse();
//        fileUploadResponse.setOriginName(file.getOriginalFilename());
//        fileUploadResponse.setName(fileUrl);
//        fileUploadResponse.setUrl(fileUrl);
//        fileUploadResponse.setUid(DateUtil.date().getTime()+"");
//        fileUploadResponse.setStatus("success");

        return new Result().ok(response);
    }

    /**
     * 生成唯一文件名（添加安全后缀检查）
     */
    private String generateUniqueFileName(String originalFilename, String fileExtension) {
        String datePath = LocalDate.now().format(DATE_FORMATTER);
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 如果文件没有扩展名，使用默认扩展名
//        if (StringUtils.isBlank(fileExtension)) {
//            fileExtension = "dat";
//        }

        return String.format("%s/%s/%s/%s",
                ossConf.getRootDirectory(),
                datePath,
                uuid,
                originalFilename);
    }

    /**
     * 生成文件访问URL
     */
    private String generateFileUrl(String fileName) {
        return String.format("https://%s.%s/%s",
                ossConf.getBucketName(),
                ossConf.getEndpoint().replace("https://", ""),
                fileName);
    }
}